//
//  AppDelegate.m
//  SportSocial
//
//  Created by yull on 14/11/19.
//  Copyright (c) 2014年 yull. All rights reserved.
//

#import "AppDelegate.h"

#import "Interface.h"
#import "IM_Service.h"
#import "LocationManager.h"

#import <Reachability.h>

#pragma mark - 分享和第三方登陆
#import "WeiboSDK.h"
#import <TencentOpenAPI/QQApiInterface.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import <ShareSDK/ShareSDK.h>
#import "WXApi.h"

#import <MobClick.h>

@interface AppDelegate () <WeiboSDKDelegate,WXApiDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [MobClick startWithAppkey:@"5502751ffd98c539ca000e59"];
    
    [self judgeFirstUse];
    
    [self registerNotificaton];
    
    [[Reachability reachabilityForInternetConnection] startNotifier];
    
    [self initShareSDK];
    
    [self createPath];
    
    [[IM_Service instance] prepare];
    
    [WeiboSDK registerApp:@"2027272542"];
    [WXApi registerApp:@"wx33b70d269130d078"];
    
    manager = [[BMKMapManager alloc] init];
    BOOL ret = [manager start:@"A5FhPSf4O5IWTT65ztxU0XE2" generalDelegate:nil];
    if (ret) {
        NSLog(@"地图服务启动成功!");
        
        [LocationManager shareInstance];
    }else {
        NSLog(@"地图服务启动失败!");
    }
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor clearColor];
    
    RESideMenu *menu = [Interface createSideMenu];
    
    self.window.rootViewController = menu;
    
    [self.window makeKeyAndVisible];
    
    return YES;
}

- (void)judgeFirstUse
{
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    BOOL haveUse = [[userDefault objectForKey:@"HaveUse"] boolValue];
    
    if (!haveUse) {
        [userDefault setObject:[NSNumber numberWithBool:YES] forKey:@"HaveUse"];
        [userDefault setObject:[NSNumber numberWithBool:YES] forKey:@"SoundAlert"];
        [userDefault synchronize];
    }
}

- (void)createPath
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL isDirectory = YES;
    BOOL result;
    
    NSString *dbDir = [FunctionMethod dbDirectoryPath];
    
    if (![fileManager fileExistsAtPath:dbDir isDirectory:&isDirectory]) {
        result = [fileManager createDirectoryAtPath:dbDir withIntermediateDirectories:YES attributes:nil error:nil];
        if (!result) {
            NSLog(@"创建数据库文件夹失败!");
        }
    }
    
    NSString *audioDir = [FunctionMethod audioDiretoryPath];
    
    if (![fileManager fileExistsAtPath:audioDir isDirectory:&isDirectory]) {
        result = [fileManager createDirectoryAtPath:audioDir withIntermediateDirectories:YES attributes:nil error:nil];
        if (!result) {
            NSLog(@"创建音频文件夹失败!");
        }
    }
    
    NSString *picDir = [FunctionMethod picDiretoryPath];
    
    if (![fileManager fileExistsAtPath:picDir isDirectory:&isDirectory]) {
        result = [fileManager createDirectoryAtPath:picDir withIntermediateDirectories:YES attributes:nil error:nil];
        if (!result) {
            NSLog(@"创建图片文件夹失败!");
        }
    }
    
}
- (void)applicationWillResignActive:(UIApplication *)application {
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[IM_Service instance] disconnectService];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [[IM_Service instance] connect];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    
}

- (void)applicationWillTerminate:(UIApplication *)application {
    
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    [TencentOAuth HandleOpenURL:url];
    [WeiboSDK handleOpenURL:url delegate:self];
    [WXApi handleOpenURL:url delegate:self];
    return [ShareSDK handleOpenURL:url wxDelegate:self];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    [TencentOAuth HandleOpenURL:url];
    [WeiboSDK handleOpenURL:url delegate:self];
    [WXApi handleOpenURL:url delegate:self];
    return [ShareSDK handleOpenURL:url sourceApplication:sourceApplication annotation:annotation wxDelegate:self];
}

-(void) onResp:(BaseResp*)resp
{
    if (resp.errCode == 0) {
        NSLog(@"微信授权成功！");
        
        SendAuthResp *authResp = (SendAuthResp *)resp;
        NSString *code = authResp.code;
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"WeixinLoginSuccess" object:nil userInfo:@{@"code":code}];
    } else {
        NSLog(@"授权失败！");
    }
}

#pragma mark - WeiboSDKDelegate

- (void)didReceiveWeiboRequest:(WBBaseRequest *)request
{
    
}

- (void)didReceiveWeiboResponse:(WBBaseResponse *)response
{
    if (response.statusCode == WeiboSDKResponseStatusCodeSuccess) {
        NSLog(@"微博授权成功!");
        
        WBAuthorizeResponse *authorizeResponse = (WBAuthorizeResponse *)response;
        NSString *userId = authorizeResponse.userID;
        NSString *accessToken = authorizeResponse.accessToken;
        
        NSDictionary *userInfo = @{@"userId":userId,
                                   @"accessToken":accessToken};
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"SinaWeiboLoginSuccess" object:nil userInfo:userInfo];
    }else {
        NSLog(@"授权失败!");
    }
}

- (void)initShareSDK
{
    [ShareSDK registerApp:@"11c19a199cac"];//字符串api20为您的ShareSDK的AppKey
    
    //添加新浪微博应用 注册网址 http://open.weibo.com
    [ShareSDK connectSinaWeiboWithAppKey:@"2027272542"
                               appSecret:@"38b0351ff43cdb3a95eba342fd4afc79"
                             redirectUri:@"https://api.weibo.com/oauth2/default.html"];
    //当使用新浪微博客户端分享的时候需要按照下面的方法来初始化新浪的平台
    [ShareSDK  connectSinaWeiboWithAppKey:@"2027272542"
                                appSecret:@"38b0351ff43cdb3a95eba342fd4afc79"
                              redirectUri:@"https://api.weibo.com/oauth2/default.html"
                              weiboSDKCls:[WeiboSDK class]];
    //添加QQ应用  注册网址  http://open.qq.com/
    [ShareSDK connectQQWithQZoneAppKey:@"1104446359"
                     qqApiInterfaceCls:[QQApiInterface class]
                       tencentOAuthCls:[TencentOAuth class]];
    
    //添加微信应用 注册网址 http://open.weixin.qq.com
    [ShareSDK connectWeChatWithAppId:@"wx33b70d269130d078"
                           appSecret:@"6487a89709eceda2cf8b6c97b72889f8"
                           wechatCls:[WXApi class]];
}

- (void)logOut
{
    RESideMenu *menu = (RESideMenu *)self.window.rootViewController;
    
    UITabBarController *tabbarController = (UITabBarController *)menu.contentViewController;
    
    UINavigationController *navigation = (UINavigationController *)tabbarController.selectedViewController;
    [navigation popToRootViewControllerAnimated:YES];
    
    tabbarController.selectedIndex = 1;
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您的账号已在别处登录!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
}

#pragma mark - 消息通知
- (void)registerNotificaton
{
    
#ifdef __IPHONE_8_0
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        
        UIUserNotificationSettings *settings = nil;
        
        settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert categories:nil];
        
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }  else {
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeNone;
        
        
        myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
    }
#else
    UIRemoteNotificationType myTypes = UIRemoteNotificationTypeNone;
    
    
    myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
    
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
#endif
}

- (void)unregisterNotification
{
    [[UIApplication sharedApplication] unregisterForRemoteNotifications];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSString *dt = [[[NSString stringWithFormat:@"%@", deviceToken] stringByReplacingOccurrencesOfString:@"<" withString:@""] stringByReplacingOccurrencesOfString:@">" withString:@""];
    dt = [dt stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"deviceToken:%@", dt);
    [CurrentUser shareInstance].deviceToken = dt;
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"%@",error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    NSLog(@"收到推送消息:%@",userInfo);
}

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    //注册远程通知
    [application registerForRemoteNotifications];
}

@end
